<template>
  <div ref="article-list">
    <van-pull-refresh
      v-model="refreshing"
      @refresh="onRefresh"
      :success-text="refreshSuccessText"
      :success-duration="1000"
      class="article-list"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <article-item
          v-for="item in articleList"
          :key="item.id"
          :articleInfo="item"
        ></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { debounce } from 'lodash'
import ArticleItem from '@/components/article-item'
import { apiGetArticleList } from '@/api/article'
export default {
  name: 'ArticleList',
  components: { ArticleItem },
  props: {
    channelInfo: {
      type: Object,
      require: true
    }
  },
  data() {
    return {
      articleList: [],
      loading: false,
      finished: false,
      timestamp: null,
      refreshing: false,
      refreshSuccessText: '',
      scrollTopNum: 0
    }
  },

  // 组件第一次创建时加载，后续切换到该组件后不在执行
  created() {
    // console.log('created')
    // this.getArticleList()
  },
  mounted() {
    // 获取滚动到的地方位置
    // TODO 不生效
    const domArticleList = this.$refs['article-list']
    // console.log(domArticleList, '------------')
    domArticleList.onscroll = debounce(() => {
      console.log(domArticleList.scrollTop)
      this.scrollTopNum = domArticleList.scrollTop
    }, 50)
  },
  // keeplive 下的组件激活周期函数
  activated() {
    // 把记录到的 top 数据重新设置回去
    this.$refs['article-list'].scrollTop = this.scrollTopNum
  },
  methods: {
    async onLoad() {
      const { data } = await apiGetArticleList({
        channel_id: this.channelInfo.id,
        timestamp: this.timestamp || Date.now(),
        with_top: 1
      })

      // console.log(data)

      if (data.data.results.length === 0) {
        this.finished = true
      } else {
        this.timestamp = data.data.pre_timestamp
        this.articleList.push(...data.data.results)
      }
      this.loading = false
    },
    async onRefresh() {
      const { data } = await apiGetArticleList({
        channel_id: this.channelInfo.id,
        timestamp: Date.now(),
        with_top: 1
      })

      this.refreshSuccessText = `成功获取了 ${data.data.results.length} 条`
      this.refreshing = false

      this.articleList = data.data.results
    }
  }
}
</script>

<style lang="less" scoped>
.article-list {
  position: fixed;
  left: 0;
  right: 0;
  top: 90px;
  bottom: 50px;
  overflow-y: auto;
}
</style>
